#! /usr/bin/env/python3
# _*_ coding:UTF-8 _×_
'''
    网络爬虫
    作者：王楠
    日期：2020/03/03
    版本：5.0:网络爬虫
         6.0:bs4 beautifulsoup4
'''

import requests    # 网络方法
from bs4 import BeautifulSoup
import threading
import time
import csv


def get_aqi():
    '''
    获取网页的内容,返回文本
    '''
    url = 'http://pm25.in/'+city
    r = requests.get(url, timeout=30)
    # print('输出r.text:\n', r.text)
    soup = BeautifulSoup(r.text, 'html')
    # print('输出ｓｏｕｐ：\n', soup)
    div_list = soup.find_all('div', {'class': 'span1'})
    live_time = soup.find('div', class_='live_data_time').text.strip()
    live_time_l = live_time.split('：')
    print('查询时间：', time.strftime('%Y-%m-%d %H:%M:%S'))
    print(live_time)
    print('空气质量情况如下：')
    aqi_dict = dict()
    for i in range(8):
        div_content = div_list[i]
        # print(div_content)
        key = div_content.find('div', {'class': 'caption'}).text.strip()
        value = div_content.find('div', {'class': 'value'}).text.strip()
        aqi_dict[key] = value
        print(key+':' + value)
    with open('/home/wangnan/文档/python/小象学院/09 空气指数/AQI_'+city+time_now+'_.csv', 'a', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        time_now_l = ['查询时间：', time.strftime('%Y-%m-%d %H:%M:%S')]
        writer.writerow(time_now_l)
        writer.writerow(live_time_l)
        city_l = ['城市：', city]
        writer.writerow(city_l)
        live_time_l = [live_time]
        writer.writerow(live_time_l)
        # print(aqi_dict.keys())
        # print(aqi_dict.values())
        # print(list(aqi_dict.keys()))
        # print(list(aqi_dict.values()))
        writer.writerow(aqi_dict.keys())
        writer.writerow(aqi_dict.values())
    # print(aqi_dict)
    # for key, val in aqi_dict.items():
    #    print(key+' : '+val)
    timer = threading.Timer(space_time_chick, get_aqi)
    timer.start()


def main():
    '''
    主函数
    '''
    global space_time_chick, city, timer, time_now
    time_now = time.strftime('%Y-%m-%d %H:%M:%S')
    print(time_now)
    # print(type(time_now))
    print('这是一个ｐｍ2.5查询工具')
    city = input('请输入要查询城市的拼音:')
    space_time_chick = int(input('请输入查询间隔时间(min)：'))
    timer = threading.Timer(1, get_aqi)
    timer.start()


if __name__ == '__main__':

    main()
